#include "App_IO.h"

extern TaskHandle_t fingerScanTaskHandle;
extern TaskHandle_t otaTaskHandle;
/* 存储数字对应的字符  1 => '1'  ...*/
char    inputBuff[50] = {0};
uint8_t inputBuffeLen = 0;   // 缓冲区存储的字符的长度

static Pwd_handle_state_t pwdState = CHECK_PWD;
void                      App_IO_Start(void)
{
    MY_LOGI("1. 初始化触摸按键");
    Inf_SC12B_Init();
    MY_LOGI("2. 初始化led");
    Inf_LED_Init();
    MY_LOGI("3. 初始化语音");
    Inf_WTN6_Init();
    MY_LOGI("4. 初始化nvs");
    Dri_NVS_Init();
    MY_LOGI("5. 电机初始化");
    Inf_BDR6120_Init();
    MY_LOGI("6. 初始化指纹模块");
    //Inf_FPM385_Init();
}

/*
按键类型:
    数字  shart  M

    sharp: 表示输入的结束


    M: 不用. 如果输入M, 不处理,并且输出语音: 非法操作


*/
void App_IO_TouchKeyScan(void)
{

    /*
        定义输入状态机:
            free: 默认状态
                在free状态下, 有按键按下, 激活键盘
                    然后进入input
            input:
                读取数据的键, 然后存储

                如果碰到sharp 表示输入结束 进入到complete

                如果碰到M表示非法输入, 回到free

            complete:
                对输入进行处理

                处理结束, 进入free
    */
    Touch_Key_t key = Inf_SC12B_ReadTouchKey();

    static Input_State_t state = FREE;

    if(key == key_no)
    {
        state = FREE;
        Inf_LED_LightAll(black);

        return;
    }

    switch(state)
    {
        case FREE: /* 在free状态, 有按键按下, 激活键盘 */
        {
            Inf_LED_LightAll(white);
            memset(inputBuff, 0, sizeof(inputBuff));
            inputBuffeLen = 0;
            state         = INPUT;

            pwdState = CHECK_PWD; /* 恢复到默认状态 */
            break;
        }

        case INPUT:
        {
            sayWaterDrop();
            Inf_LED_LightKeyLed(key, blue);
            if(key == key_M)
            {
                sayIllegalOperation();
                state = FREE;
            }
            else if(key == key_sharp)
            {
                // 对输入进入处理
                App_IO_HandleInput();
                if(pwdState == ADD_PWD || pwdState == DEL_PWD)
                {
                    /* 后面的输入是要添加或者删除的密码 */
                    memset(inputBuff, 0, sizeof(inputBuff));
                    inputBuffeLen = 0;
                }
                else
                {
                    state = FREE;
                    vTaskDelay(500);
                    Inf_LED_LightAll(black);
                }
            }
            else /* 输入的是数字 */
            {
                inputBuff[inputBuffeLen++] = key + '0';
            }
            break;
        }
        default:
            break;
    }
}

/**
 * @description: 对输入做处理
 *     命令  2个数字表示命令
 *          密码相关
 *              00   添加密码
 *              01   删除密码
 *              ...
 *
 *          指纹相关
 *              10  录入指纹
 *              11  删除指纹
 *                  ...
 *
 *          ota相关
 *              20  升级固件
 *                  ...
 *
 *     密码
 *          >= 6  输入的是密码
 *
 *
 *      错误
 *          <=1  || =3|| =4|| =5
 *
 * @return {*}
 */
void App_IO_HandleInput(void)
{
    MY_LOGE("输入: %s", inputBuff);

    if(inputBuffeLen <= 1 || inputBuffeLen == 3 || inputBuffeLen == 4 || inputBuffeLen == 5)
    {
        sayIllegalOperation();
    }
    else if(inputBuffeLen == 2)
    {
        /* 输入的是命令 */
        if(inputBuff[0] == '0')
        {
            if(inputBuff[1] == '0')
            {
                sayAddUser();
                vTaskDelay(1000);
                sayInputUserPassword();

                pwdState = ADD_PWD;
            }
            else if(inputBuff[1] == '1')
            {
                sayDelUser();
                vTaskDelay(1000);
                sayInputUserPassword();

                pwdState = DEL_PWD;
            }
        }
        else if(inputBuff[0] == '1')
        {
            //  指纹相关操作  '0'  '1' 发送
            xTaskNotify(fingerScanTaskHandle, (uint32_t)inputBuff[1], eSetValueWithOverwrite);
        }
        else if(inputBuff[0] == '2')
        {
            // ota相关操作
            xTaskNotify(otaTaskHandle, (uint32_t)inputBuff[1], eSetValueWithOverwrite);
        }
    }
    else
    {
        /* 正常输入的密码 */

        if(pwdState == ADD_PWD)
        {
            MY_LOGE("添加密码: %s", inputBuff);
            /* 添加密码 */
            App_IO_AddPwd();
            pwdState = CHECK_PWD;
        }
        else if(pwdState == DEL_PWD)
        {
            MY_LOGE("删除密码: %s", inputBuff);
            /* 删除密码 */
            App_IO_DelPwd();
            pwdState = CHECK_PWD;
        }
        else if(pwdState == CHECK_PWD)
        {
            MY_LOGE("验证密码: %s", inputBuff);
            /* 验证密码: 开锁 */
            App_IO_CheckPwd();
        }
    }
}

/*
密码存储:
    1. 存储到什么地方
            非易失性存储设备
            nvs  esp32芯片内部flash提供的一块空间

    2. 存储的格式
         键值对形式

         键             值
         id(自增)       密码
         麻烦

         ------
         密码          随意



*/
void App_IO_AddPwd(void)
{
    esp_err_t err = Dri_NVS_WriteI8(inputBuff, 0);
    if(err == ESP_OK)
    {
        MY_LOGE("密码: %s 添加成功", inputBuff);
        sayPasswordAddSucc();
    }
    else
    {
        MY_LOGE("密码: %s 添加失败", inputBuff);
        sayPasswordAddFail();
    }
}

void App_IO_DelPwd(void)
{
    esp_err_t err = Dri_NVS_DelKey(inputBuff);
    if(err == ESP_OK)
    {
        MY_LOGE("密码: %s 删除成功", inputBuff);
        sayPassword();
        vTaskDelay(500);
        sayDelSucc();
    }
    else
    {
        MY_LOGE("密码: %s 删除失败", inputBuff);
        sayPassword();
        vTaskDelay(500);
        sayDelFail();
    }
}

void App_IO_CheckPwd(void)
{
    if(Dri_NVS_IsKeyMatch(inputBuff) == ESP_OK)
    {
        MY_LOGE("密码: %s 验证成功", inputBuff);
        sayPasswordVerifySucc();
        Inf_BDR6120_OpenLock();
        sayDoorOpen();
    }
    else
    {
        MY_LOGE("密码: %s 验证失败", inputBuff);
        sayPasswordVerifyFail();
    }
}

void App_IO_FingerScan(void)
{
    static uint8_t fingerState = finger_check; /* 指纹操作状态 */
    uint32_t       action      = 0;
    xTaskNotifyWait(0, 0, &action, portMAX_DELAY);

    if(action == '0')
    {
        /* 绿灯闪烁 */
        LED_GREEN_FLICKER;

        sayAddUserFingerprint();
        vTaskDelay(1500 / portTICK_PERIOD_MS);
        sayPlaceFinger();

        fingerState = finger_add;
    }
    else if(action == '1')
    {
        /* 红灯闪 */
        LED_RED_FLICKER;

        sayDelUserFingerprint();
        vTaskDelay(1500 / portTICK_PERIOD_MS);
        sayPlaceFinger();

        fingerState = finger_del;
    }
    else if(action == '2')
    {
        switch(fingerState)
        {
            case finger_add:
            {
                MY_LOGE("录入指纹");
                Inf_FPM385_AutoEnroll();

                LED_COLOR_OFF;
                break;
            }

            case finger_del:
            {
                MY_LOGE("删除指纹");
                Inf_FPM385_Delfinger();

                LED_COLOR_OFF;
                break;
            }

            case finger_check:
            {
                LED_BLUE_ON;
                MY_LOGE("验证指纹");

                Inf_FPM385_AutoVerify();
                LED_COLOR_OFF;
                break;
            }
            default:
                break;
        }

        Inf_FPM385_Sleep();
        fingerState = finger_check;
    }
}

void App_IO_nvs_test(void)
{

    /* 测试nvs读写 */
    /* Dri_NVS_WriteI8("345678", 0);
    Dri_NVS_WriteI8("123456", 0);
    Dri_NVS_WriteI8("223344", 0); */

    if(Dri_NVS_IsKeyMatch("1234") == ESP_OK)
    {
        MY_LOGE("1234 查找成功");
    }
    else
    {
        MY_LOGE("1234 查找失败");
    }

    if(Dri_NVS_IsKeyMatch("123456") == ESP_OK)
    {
        MY_LOGE("123456 查找成功");
    }
    else
    {
        MY_LOGE("123456 查找失败");
    }

    if(Dri_NVS_IsKeyMatch("2212345633") == ESP_OK)
    {
        MY_LOGE("2212345633 查找成功");
    }
    else
    {
        MY_LOGE("2212345633 查找失败");
    }

    if(Dri_NVS_DelKey("123456") == ESP_OK)
    {
        MY_LOGE("123456 删除成功");
    }
    else
    {
        MY_LOGE("123456 删除失败");
    }

    if(Dri_NVS_IsKeyMatch("123456") == ESP_OK)
    {
        MY_LOGE("123456 查找成功");
    }
    else
    {
        MY_LOGE("123456 查找失败");
    }
}
